package com.example.filesystem.util;

import org.apache.tika.Tika;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class ContentType {
    private static Tika tika;

    public static String getContentType(Path filePath) {
        // 优先级1：系统内容检测
        try {
            String type = Files.probeContentType(filePath);
            if (type != null) {
                return type;
            }
        } catch (IOException ignored) {
        }

        // 优先级2：Tika内容检测
        if (tika == null) {
            tika = new Tika();
        }
        try {
            String type = tika.detect(filePath);
            if (!type.equals("application/octet-stream")) {
                return type;
            }
        } catch (Throwable ignored) {
        }

        // 优先级3：扩展名映射
        String fileName = filePath.getFileName().toString().toLowerCase();
        if (fileName.endsWith(".webp")) return "image/webp";
        if (fileName.endsWith(".epub")) return "application/epub+zip";
        if (fileName.endsWith(".md")) return "text/markdown";
        //兜底
        return "application/octet-stream";
    }
}
